# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  helper :prototype_window_class
  session :session_key => '_droplet_session_id'
  layout 'application'

  def do_authorise (action, params)
    # This is a hack, which should be fixed once Goldberg release new version which allow more flexible control
    if Goldberg.user.role_id == 3
      return true
    end

#    puts self.actions_to_check.inspect
    if !self.actions_to_check[action.intern].nil?
      permissions_to_check = self.actions_to_check[action.intern]
#      puts permissions_to_check.inspect
#      puts self.actions_to_check.inspect
      permissions_to_check.each do |permission|

        if self.respond_to?(action+'_'+permission+'_authorise')
          self.send(action+'_'+permission+'_authorise', params)
        else
          if self.respond_to?(permission+'_authorise')
            permission_params = {}
            if self.respond_to?('build_'+permission+'_params')
              self.send('build_'+permission+'_params', permission_params, params)
            end
            if self.respond_to?(self.controller_name+'_build_'+permission+'_params')
              self.send(self.controller_name+'_build_'+permission+'_params', permission_params, params)
            end
  #          puts permission_params.inspect
            #puts permission_params.inspect
            if self.send(permission+'_authorise', permission_params)
              return true
            end
          end
         end
      end
      return false
    end
    return true
  end

  def owner_authorise permission_params
    authorised = false
    #puts permission_params[:id].inspect

    if is_numeric?(permission_params[:id])
      #puts to_model_name(self.controller_name)
      begin
        model_class = Module.const_get(to_model_name(self.controller_name))
        @result = model_class.find(permission_params[:id])
#        puts @result.inspect
#        puts Goldberg.user.id.inspect
        if @result.user_id == Goldberg.user.id
          authorised = true
        end
      rescue
      end
    end

    return authorised
  end

  def build_owner_params permission_params, params
    permission_params.merge!({:id => params[:id]})
  end

  def private_authorise permission_params
    if (permission_params[:private]) == 0
      return true
    end

    # yes? do you have access key?
    if !permission_params[:access_key].nil? && permission_params[:access_key].length == 40
      @invitation = Invitation.find(:first, :conditions => {:group_id => permission_params[:group_id], :access_key => permission_params[:access_key]})
#      @invitation = Invitation.find(:all, :conditions => {:group_id => 12})
#      puts @invitation.size
      if @invitation.size > 0
#        puts @invitation.id
#        Invitation.delete(@invitation.id)  #remove it
        return true
      end
    end

    @result = Group.find_by_sql ["SELECT * from groups_users WHERE group_id =? AND user_id = ? LIMIT 1", permission_params[:group_id], Goldberg.user.id]
    if @result.size > 0
      return true
    end

    return false
  end

  def build_private_params permission_params, params
     permission_params.merge!({:id => params[:id],
                               :access_key => params[:access_key]})
  end

  def images_build_private_params permission_params, params
    @result = Image.find(:first, :conditions => ["images.id = ?", permission_params[:id]], :include => [:group])
    permission_params.merge!({:group_id => @result.group.id,
                          :private => @result.group.private})
  end

  def groups_build_private_params permission_params, params
    @result = Group.find(:first, :conditions => ["id = ?", permission_params[:group_id]])
    permission_params.merge!({:group_id => @result.group_id,
                          :private => @result.private})
  end

  def is_numeric?(s)
    return (s.to_s =~ /^\d+(\.\d+|\d*)$/)?true:false
  end

  def to_model_name( string )
    string.to_s.gsub( /_id/, '' ).singularize.split( '_' ).collect { |word| word.capitalize }.join
  end
end
